package com.actions.bluetoothbox2.fragment;

import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actions.bluetoothbox2.R;
import com.actions.bluetoothbox2.app.BrowserActivity;
import com.actions.bluetoothbox2.util.Constant.IPCKey;
import com.actions.bluetoothbox2.util.PopupMusicSelecter;
import com.actions.bluetoothbox2.util.Preferences;
import com.actions.bluetoothbox2.widget.AlarmClockTimePicker;
import com.actions.bluetoothbox2.widget.Wakeuplighttime;
import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData.AlarmEntry;
import com.actions.ibluz.manager.BluzManagerData.FolderEntry;
import com.actions.ibluz.manager.BluzManagerData.RingEntry;
import com.actions.ibluz.manager.BluzManagerData.RingSource;
import com.actions.ibluz.manager.IAlarmManager;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class AlarmClockSettingFragment extends SherlockFragment {
    private static final String TAG = "AlarmClockSettingFragment";

    private BrowserActivity mActivity;
    private View mView;
    private IAlarmManager mAlarmManager;
    private BluzManager mBluzManager;

    private AlarmEntry mAlarmEntry;
    private AlarmClockTimePicker mTimePicker;
    private EditText mTitleEditText;

    private CheckBox[] mRepeatButtons = new CheckBox[7];
    private Spinner mAlarmTypeSpinner;
    private ImageView img_selected_music;
    private Button img_select_music;
    //    private Spinner mAlarmMusicSpinner;
    private List<String> mAlarmType = new ArrayList<String>();
    private List<RingEntry> mUhostEntries = new ArrayList<RingEntry>();
    private List<RingEntry> mCardEntries = new ArrayList<RingEntry>();
    private List<RingEntry> mInternalEntries = new ArrayList<RingEntry>();
    private List<RingEntry> mRadioEntries = new ArrayList<RingEntry>();
    private List<RingEntry> mCurrentEntries;

    private TextView tv__light_time;
    private SeekBar seekbar_light_time;

    private ArrayAdapter<String> mAlarmTypeSpinnerAdapter;
    private ArrayAdapter<String> mAlarmMusicSpinnerAdapter;

    private Button mCommitButton;
    private Button mCancelButton;

    private static final String mPreFix[] = {"bd0_", "bd1_", "bd2_"};
    private List<FolderEntry> mFolderEntryList = new ArrayList<FolderEntry>();
    private String[] mFolderType;
    private List<RingEntry> mEXTERNAL1Entries = new ArrayList<RingEntry>();
    private List<RingEntry> mEXTERNAL2Entries = new ArrayList<RingEntry>();
    private List<RingEntry> mEXTERNAL3Entries = new ArrayList<RingEntry>();
    private List<RingEntry> mEXTERNAL4Entries = new ArrayList<RingEntry>();
    private HashMap<Integer, List<RingEntry>> mEXTERNALMap = new HashMap<Integer, List<RingEntry>>();
    private Menu mMenu = null;
    private Wakeuplighttime mWakeuplighttime;
    private PopupMusicSelecter popupMusicSelecter;
    private int select_position = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();
        if (bundle != null) {
            mAlarmEntry = bundle.getParcelable(IPCKey.ALARM_ENTRY);
            mWakeuplighttime = (Wakeuplighttime) bundle.getSerializable("Second");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        mView = inflater.inflate(R.layout.alarmclock_setting, container, false);
        mActivity = (BrowserActivity) getActivity();
        mActivity.mGlobalInfoLayout.setVisibility(View.GONE);
//            mAlarmManager = mActivity.getIBluzManager().getAlarmManager(null);
        if (mActivity.getBluzManager() != null) {
            mBluzManager = mActivity.getBluzManager();
            mAlarmManager = mBluzManager.getAlarmManager(null);
            init();
        }
        mActivity.getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        mActivity.title_back.setVisibility(View.VISIBLE);
        return mView;
    }

    public void init() {
        mTimePicker = (AlarmClockTimePicker) mView.findViewById(R.id.alarmclock_time);
        mTimePicker.setSaveFromParentEnabled(false);
        mTimePicker.setSaveEnabled(true);

        mTitleEditText = (EditText) mView.findViewById(R.id.alarmclock_edittext);
        mRepeatButtons[0] = (CheckBox) mView.findViewById(R.id.Sunday);
        mRepeatButtons[1] = (CheckBox) mView.findViewById(R.id.Monday);
        mRepeatButtons[2] = (CheckBox) mView.findViewById(R.id.Tuesday);
        mRepeatButtons[3] = (CheckBox) mView.findViewById(R.id.Wednesday);
        mRepeatButtons[4] = (CheckBox) mView.findViewById(R.id.Thursday);
        mRepeatButtons[5] = (CheckBox) mView.findViewById(R.id.Friday);
        mRepeatButtons[6] = (CheckBox) mView.findViewById(R.id.Saturday);

        mAlarmTypeSpinner = (Spinner) mView.findViewById(R.id.alarmclock_type);
//        mAlarmMusicSpinner = (Spinner) mView.findViewById(R.id.alarmclock_music);
        img_select_music = (Button) mView.findViewById(R.id.img_select_music);
        img_selected_music = (ImageView) mView.findViewById(R.id.img_selected_music);
        popupMusicSelecter = new PopupMusicSelecter(getActivity());
        img_selected_music.setImageResource(R.drawable.ic_music_1);

        tv__light_time = (TextView) mView.findViewById(R.id.tv__light_time);
        seekbar_light_time = (SeekBar) mView.findViewById(R.id.seekbar_light_time);
        seekbar_light_time.setOnSeekBarChangeListener(listener_seekbar);

        popupMusicSelecter.setSelected(new PopupMusicSelecter.onSelecteListener() {
            @Override
            public void onSelected(int position, int imgID) {
                img_selected_music.setImageResource(imgID);
                select_position = position + 1;
            }
        });

        img_select_music.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popupMusicSelecter.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
//        mAlarmMusicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                TextView tv = (TextView) view;
//                if (null != tv) {
//                    tv.setTextColor(getResources().getColor(R.color.white));
//                }
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//            }
//        });
        mUhostEntries.clear();
        mCardEntries.clear();
        mEXTERNAL1Entries.clear();
        mEXTERNAL2Entries.clear();
        mEXTERNAL3Entries.clear();
        mEXTERNAL4Entries.clear();
        mEXTERNALMap.clear();
        for (RingEntry entry : mAlarmManager.getRingList()) {
            switch (entry.source) {
                case RingSource.UHOST:
                    mUhostEntries.add(entry);
                    break;
                case RingSource.CARD:
                    mCardEntries.add(entry);
                    break;
                case RingSource.INTERNAL:
                    mInternalEntries.add(entry);
                    break;
                case RingSource.EXTERNAL1:
                    mEXTERNAL1Entries.add(entry);
                    break;
                case RingSource.EXTERNAL2:
                    mEXTERNAL2Entries.add(entry);
                    break;
                case RingSource.EXTERNAL3:
                    mEXTERNAL3Entries.add(entry);
                    break;
                case RingSource.EXTERNAL4:
                    mEXTERNAL4Entries.add(entry);
                    break;
                default:
                    break;
            }
        }
        mEXTERNALMap.put(0, mEXTERNAL1Entries);
        mEXTERNALMap.put(1, mEXTERNAL2Entries);
        mEXTERNALMap.put(2, mEXTERNAL3Entries);
        mEXTERNALMap.put(3, mEXTERNAL4Entries);
        final List<String> typeString = new ArrayList<String>();
        typeString.add(getResources().getString(R.string.alarmclock_uhost));
        typeString.add(getResources().getString(R.string.alarmclock_cardsong));
        typeString.add(getResources().getString(R.string.alarmclock_fm));
        typeString.add(getResources().getString(R.string.alarmclock_bell));

        if (mInternalEntries.size() > 0) {
            mAlarmType.add(typeString.get(3));
        }
        mFolderEntryList = mAlarmManager.getRingFolderList();
        if (mFolderEntryList.size() > 0) {
            mFolderType = new String[mFolderEntryList.size()];
            for (int i = 0; i < mFolderEntryList.size(); i++) {
                mFolderType[i] = mFolderEntryList.get(i).name;
                typeString.add(mFolderEntryList.get(i).name);
                if (!mEXTERNALMap.get(i).isEmpty()) {
                    mAlarmType.add(mFolderEntryList.get(i).name);
                }
            }
        } else {
            mFolderType = new String[]{"", "", "", ""};
        }
        if (mCardEntries.size() > 0) {
            mAlarmType.add(typeString.get(1));
        }
        if (mUhostEntries.size() > 0) {
            mAlarmType.add(typeString.get(0));
        }
        // For the change of US282A
        /*
         * int mRadioBand = (Integer) Preferences.getPreferences(mActivity, Preferences.KEY_RADIO_BAND_SIGN, 0); int perferenceTotalChannel =
		 * getPerferenceTotalChannelNumber(mRadioBand); if (perferenceTotalChannel > 0) { mAlarmType.add(typeString.get(2)); for (int i = 1; i <=
		 * perferenceTotalChannel; i++) { int channel = (Integer) Preferences.getPreferences(getActivity(), mPreFix[mRadioBand] +
		 * Preferences.KEY_RADIO_CHANNEL_PREFIX + i, 0); RingEntry entry = new RingEntry(); entry.id = channel; entry.source = RingSource.FM; entry.name =
		 * String.valueOf(((float) channel) / 1000); mRadioEntries.add(entry); } }
		 */
        mAlarmTypeSpinnerAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, mAlarmType);
        mAlarmTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mAlarmTypeSpinner.setAdapter(mAlarmTypeSpinnerAdapter);
        mAlarmTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Spinner spinner = (Spinner) parent;
                String type = (String) spinner.getItemAtPosition(position);

                if (type.equalsIgnoreCase(typeString.get(0))) {
                    mAlarmEntry.ringType = RingSource.UHOST;
                    mCurrentEntries = mUhostEntries;
                } else if (type.equalsIgnoreCase(typeString.get(1))) {
                    mAlarmEntry.ringType = RingSource.CARD;
                    mCurrentEntries = mCardEntries;
                } else if (type.equalsIgnoreCase(typeString.get(3))) {
                    mAlarmEntry.ringType = RingSource.INTERNAL;
                    mCurrentEntries = mInternalEntries;
                } else if (type.equalsIgnoreCase(mFolderType[0])) {
                    mAlarmEntry.ringType = RingSource.EXTERNAL1;
                    mCurrentEntries = mEXTERNAL1Entries;
                } else if (type.equalsIgnoreCase(mFolderType[1])) {
                    mAlarmEntry.ringType = RingSource.EXTERNAL2;
                    mCurrentEntries = mEXTERNAL2Entries;
                } else if (type.equalsIgnoreCase(mFolderType[2])) {
                    mAlarmEntry.ringType = RingSource.EXTERNAL3;
                    mCurrentEntries = mEXTERNAL3Entries;
                } else if (type.equalsIgnoreCase(mFolderType[3])) {
                    mAlarmEntry.ringType = RingSource.EXTERNAL4;
                    mCurrentEntries = mEXTERNAL4Entries;
                } else {
                    mAlarmEntry.ringType = RingSource.FM;
                    mCurrentEntries = mRadioEntries;
                }

                String[] mRingNames = new String[mCurrentEntries.size()];
                for (int i = 0; i < mCurrentEntries.size(); i++) {
                    mRingNames[i] = mCurrentEntries.get(i).name;
                    if (mAlarmEntry.ringType == RingSource.FM) {
                        mRingNames[i] = mRingNames[i] + "MHz";
                    }
                }
                mAlarmMusicSpinnerAdapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_spinner_item, mRingNames);
                mAlarmMusicSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//                mAlarmMusicSpinner.setAdapter(mAlarmMusicSpinnerAdapter);
                int selection = 0;
                for (int i = 0; i < mCurrentEntries.size(); i++) {
                    if (mAlarmEntry.ringType == RingSource.FM) {
                        if (mAlarmEntry.ringId == mCurrentEntries.get(i).id) {
                            selection = i;
                            break;
                        }
                    } else {
                        if ( mAlarmEntry.ringId == mCurrentEntries.get(i).id) {
                            selection = i;
                            break;
                        }
                    }
                }
//                mAlarmMusicSpinner.setSelection(selection);
//                Log.i("TAG","----ringId===" + mAlarmEntry.ringId);

                mAlarmTypeSpinner.setVisibility(View.GONE);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        String ringType = typeString.get(mAlarmEntry.ringType);
        int position = 0;
        for (int i = 0; i < mAlarmType.size(); i++) {
            if (mAlarmType.get(i).equalsIgnoreCase(ringType)) {
                position = i;
                break;
            }
        }
        mAlarmTypeSpinner.setSelection(position);

        mCommitButton = (Button) mView.findViewById(R.id.commit);
        mCancelButton = (Button) mView.findViewById(R.id.cancel);

        mTimePicker.setCurrentHour(mAlarmEntry.hour);
        mTimePicker.setCurrentMinute(mAlarmEntry.minute);
        mTitleEditText.setText(mAlarmEntry.title);
        if (null != mWakeuplighttime) {
            seekbar_light_time.setProgress(mWakeuplighttime.wakeup_light_time);
            img_selected_music.setImageResource(popupMusicSelecter.imgID[mWakeuplighttime.ringId -1]);
            select_position = mWakeuplighttime.ringId;
        }
        for (int i = 0; i < mAlarmEntry.repeat.length; i++) {
            mRepeatButtons[i].setSelected(mAlarmEntry.repeat[i]);
            mRepeatButtons[i].setChecked(mAlarmEntry.repeat[i]);
        }

        mCommitButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                for (int i = 0; i < mRepeatButtons.length; i++) {
                    mAlarmEntry.repeat[i] = mRepeatButtons[i].isChecked();
                }
                mAlarmEntry.title = mTitleEditText.getText().toString();//闹钟名字
                mAlarmEntry.hour = mTimePicker.getCurrentHour();
                mAlarmEntry.minute = mTimePicker.getCurrentMinute();
//                RingEntry entry = mCurrentEntries.get(mAlarmMusicSpinner.getSelectedItemPosition());

//                if (mAlarmEntry.ringType == RingSource.FM) {//id
//                    float channel = Float.parseFloat(entry.name);
//                    mAlarmEntry.ringId = (int) (channel * 1000);
//                } else {
//                mAlarmEntry.ringId = entry.id;
//                }
                mAlarmEntry.ringId = select_position;
                mAlarmEntry.state = true;
                int light_time = seekbar_light_time.getProgress();//提前亮灯时间
                mActivity.sendAlarmClock(mAlarmEntry, light_time, mAlarmEntry.repeat);
//                mAlarmManager.set(mAlarmEntry);

                switchFragment();
            }
        });

        mCancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                switchFragment();
            }
        });
        mActivity.tv_title.setText(getResources().getText(R.string.alarmclock));
//		Log.v(TAG, "init finish!");

    }

    SeekBar.OnSeekBarChangeListener listener_seekbar = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            String str = getResources().getString(R.string.snooze_minute);
            tv__light_time.setText("" + i + str);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    private void switchFragment() {
        AlarmClockFragment fragment = new AlarmClockFragment();
        mActivity.replaceFragment(fragment, SlideLeftFragment.FRAGMENT_TAG_ALARM);
    }

    private int getPerferenceTotalChannelNumber(int bandnum) {
        return (Integer) Preferences.getPreferences(getActivity(), Preferences.KEY_RADIO_CHANNEL_NUM + String.valueOf(bandnum), 0);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        mMenu = menu;
        inflater.inflate(R.menu.alarmclock_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
        mActivity.menuItemSelected(null, item.getItemId());
        return super.onOptionsItemSelected(item);
    }
}
